define(function (require, exports) {
    var $ = require('$');
    require('cookie')
    var handlebars = require('handlebars');


    //浏览器判定
    var userAgent = navigator.userAgent.toLowerCase();
    exports.browser = {
        version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
        safari: /webkit/.test( userAgent ),
        opera: /opera/.test( userAgent ),
        msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
        mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
    };


    /*城市页面跳转城市*/
    exports.goCity = function(s) {
        var url = '?action=go&' + s;
        window.location = url;
    }


    // 加入收藏
    exports.addFavorite = function (id) {
        $(id).click(function () {
            if ( document.all ) {
                try {
                    window.external.addFavorite(window.location.href, document.title);
                } catch (e) {
                    alert("加入收藏失败，请使用Ctrl+D进行添加");
                }
            } else if ( window.sidebar ) {
                window.sidebar.addPanel(document.title, window.location.href, "");
            } else {
                alert("加入收藏失败，请使用Ctrl+D进行添加");
            }
        })
    };


    exports.areaCombo = function(id, query, url){
        this.makeRequest(url, query,  function(data){
            $('#container_'+id).html(data);
            $('#'+id).val(query.aPid);
        })
    };

    exports.cateCombo = function(id, query, url){
        this.makeRequest(url, query, function(data){
            $('#container_'+id).html(data);
            $('#'+id).val(query.aPid);
        })
    };

    exports.topTip = function ($content, $close) {
        //关闭
        $close.click(function () {
            var OPTION = { expires : 7};
            exports.cookie("topTip", '1', OPTION);
            $content.slideUp();
        });
        //加载

        if ( !exports.cookie("topTip") ) {
            setTimeout(function () {
                $content.slideDown();
            }, 1000)
        }
    }

    exports.checkChId = function (v_card) {
        var iW = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1];
        var iSum = 0;
        var iC, iVal;
        for (var i = 0; i < 17; i++) {
            iC = v_card.charAt(i);
            iVal = parseInt(iC, 10);
            iSum += iVal * iW[i];
        }
        var iJYM = iSum % 11;
        var sJYM = '';
        if ( iJYM === 0 ) sJYM = "1";
        else if ( iJYM === 1 ) sJYM = "0";
        else if ( iJYM === 2 ) sJYM = "x";
        else if ( iJYM === 3 ) sJYM = "9";
        else if ( iJYM === 4 ) sJYM = "8";
        else if ( iJYM === 5 ) sJYM = "7";
        else if ( iJYM === 6 ) sJYM = "6";
        else if ( iJYM === 7 ) sJYM = "5";
        else if ( iJYM === 8 ) sJYM = "4";
        else if ( iJYM === 9 ) sJYM = "3";
        else if ( iJYM === 10 ) sJYM = "2";
        var cCheck = v_card.charAt(17).toLowerCase();
        return cCheck == sJYM;
    };

    exports.scrollShow = function (_sel) {
        var $_sel = $(_sel);
        jQuery(window).scroll(function () {
            if ( (document.documentElement.scrollTop + document.body.scrollTop) > 0 ) {
                $_sel.show();
            } else {
                $_sel.hide();
            }
        })
    };

    exports.getData = function(id, type){
        if (typeof id.selector != 'undefined') {
            return id.attr('data-'+type);
        } else if (typeof id == 'string') {
            return $('#'+id).attr('data-'+type);
        }
    };

    /**解析 html */
    exports.toHtml = function(tpl, data) {
        var template = handlebars.compile(tpl);
        return template(data);
    };
    //判断是否为图片
    exports.IsImg = function(url){
        var sTemp;
        var b=false;
        var opt="jpg|gif|png|bmp|jpeg";
        var s=opt.toUpperCase().split("|");
        for (var i=0;i<s.length ;i++ ){
            sTemp=url.substr(url.length-s[i].length-1);
            sTemp=sTemp.toUpperCase();
            s[i]="."+s[i];
            if (s[i]==sTemp){
                b=true;
                break;
            }
        }
        return template(data);
    };

    exports.IsSwf = function(url){
        var sTemp;
        var b=false;
        var opt="swf";
        var s=opt.toUpperCase().split("|");
        for (var i=0;i<s.length ;i++ ){
            sTemp=url.substr(url.length-s[i].length-1);
            sTemp=sTemp.toUpperCase();
            s[i]="."+s[i];
            if (s[i]==sTemp){
                b=true;
                break;
            }
        }
        return b;
    }

    exports.scaleImage = function(o, w, h) {
        var img = new Image();
        img.src = o.src;
        if (img.width > 0 && img.height > 0) {
            if (img.width / img.height >= w / h) {
                if (img.width > w) {
                    o.width = w;
                    o.height = (img.height * w) / img.width;
                } else {
                    o.width = img.width;
                    o.height = img.height;
                }
                o.alt = img.width + "x" + img.height;
            } else {
                if (img.height > h) {
                    o.height = h;
                    o.width = (img.width * h) / img.height;
                } else {
                    o.width = img.width;
                    o.height = img.height;
                }
                o.alt = img.width + "x" + img.height;
            }
        }
    };

    exports.go = function (param, value, tripFile) {
        var stringObj = window.location.href;
        if ( typeof tripFile == 'undefined' ) {
            tripFile = window.location.pathname;
        }
        var lstr = "&";

        if ( stringObj.indexOf(tripFile + '?') == -1 ) {
            lstr = "?";
        }
        if ( param != 'page' )
            stringObj = stringObj.replace(/page=[0-9]*/, '');
        if ( param == 'kw' )
            stringObj = stringObj.replace(/kw=[^`]*/, 'kw=');
        var reg = new RegExp(param + "=[0-9a-zA-Z,-]*", "g"); //创建正则RegExp对象
        var urlGo = "";
        var ch = stringObj.indexOf(param + '=');
        if ( ch == -1 ) {
            urlGo = urlGo + stringObj + lstr + param + "=" + value;
        }
        if ( ch != -1 ) {
            urlGo = stringObj.replace(reg, param + "=" + value);
        }
        window.location = urlGo;
    }

    exports.setHomepage = function () {
        if ( document.all ) {
            document.body.style.behavior = 'url(#default#homepage)';
            document.body.setHomePage(window.location.href);
        } else if ( window.sidebar ) {
            if ( window.netscape ) {
                try {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                } catch (e) {
                    alert("该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true");
                }
            }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage', window.location.href);
        } else {
            alert('您的浏览器不支持自动自动设置首页, 请使用浏览器菜单手动设置!');
        }
    }

    // 异步读取
    exports.makeRequest = function (targetPhp, queryString, sucess) {
        $.ajax({
            async : false,
            cache : false,
            type : 'post',
            url : targetPhp,
            data : queryString,
            success : sucess
        });
    };

    // jsonp获取
    exports.makeJsonp = function (targetPhp, queryString, sucess) {
        $.getJSON(targetPhp + '&callback=?', queryString, sucess);
    };

    /**
     * 项目cookie
     * @param name
     * @param value
     * @param opt
     * @returns {*|The}
     */
    exports.cookie = function (name, value, opt) {
        var defaults = {
            path : lemon.cookie.path,
            domain : lemon.cookie.domain
        };
        var opts = $.extend(defaults, opt);
        return $.cookie(lemon.cookie.prefix + name, value, opts);
    }

    /**
     * tabs
     * @param id        tab块id
     * @param option    tab选项
     */
    exports.tabs = function(id,options){
        var defaults = {
            event:"click",
            activeClass:"active",
            tabNav:"#J_TabNav",
            tabContent:".J_TabContent"
        }
        var opts = $.extend(defaults, options);
        var $tabNav = $(opts.tabNav).children("li");
        var $tabContent = $(opts.tabContent);
        $tabNav.on(opts.event,function(){
            var tabIndex = $(this).index();
            $tabContent.eq(tabIndex).show();
            $tabContent.siblings(opts.tabContent).hide();
        })
    }
    exports.tab = function(oper,tab,selector,target1,target2){
        $(tab).find("li").bind(oper,function(){
            $(this).addClass(selector).siblings().removeClass(selector);
            var index = $(this).index();
            $(target1).eq(index).show().siblings(target1).hide();
            $(target2).eq(index).show().siblings(target2).hide();
        });
    }

    /*
     * 大图显示对应缩略图
     * @param big    大图列表ul Id
     * @param small  缩略图列表ul Id
     * */
    exports.showThumbnail = function(big,small){
        var $bigImg = $(big).find("li");
        $(small).find("li:first").children("i").show();
        $(small).find("li").each(function(index, element) {
            $(this).hover(function() {
                $(this).children("i").show();
                $(this).siblings().children("i").hide();
                $bigImg.eq(index).show().siblings().hide();
            });
        });
    }


    /*
     * 分页页码跳转
     * @param param     参数
     * @param vallue    参数值
     * @param tripFile  跳转目标文件
     */
    exports.xdChangeAndLocation = function(param, value, tripFile) {
        var stringObj = window.location.href;
        typeof tripFile == 'undefined' ? tripFile = window.location.pathname : tripFile;
        var lstr = "&";

        if (stringObj.indexOf(tripFile+'?') == -1) {
            lstr = "?";
        }
        var reg = new RegExp(param + "=[0-9a-zA-Z,]*", "g"); //创建正则RegExp对象
        var urlGo = "";
        var ch = stringObj.indexOf(param+'=');
        if (ch == -1) {
            urlGo = urlGo + stringObj + lstr + param + "=" + value;
        }
        if (ch != -1) {
            urlGo = stringObj.replace(reg, param + "=" + value);
        }
        window.location = urlGo;
    }

    /*
     * 监听input或者textarea有效值
     * @param string id 目标id或者class
     */
    exports.monitorNull = function(id){
        var defaultVal = $(id).val();
        $(id).focus(function(){
            var curVal = $.trim($(this).val());
            if(curVal == defaultVal){$(this).val("");}
        }).blur(function(){
            var curVal = $.trim($(this).val());
            if(curVal == defaultVal || curVal==""){$(this).val(defaultVal);}
        });
    }

    /*
     * 左右滑动
     * @param opt.list  滑动列表
     * @param opt.elemClass  列表中单个元素的class
     * @param opt.left 左按钮
     * @param opt.right 右按钮
     * @param opt.width 滑动宽度
     * @param opt.timer 时间间隔
     * */
    exports.slide = function(opt){
        var timerID;
        var $btnLeft = opt.left;//向左按钮
        var $btnRight = opt.right;//向右按钮
        var $this = opt.list;
        var elemClass = opt.elemClass;
        var liW = opt.width//参数：每个li的宽度（包括border,margin,padding,都要算进去）
        var speed = opt.speed ? parseInt(opt.speed, 10) : 500; //滚动速度，数值越大，速度越慢（毫秒）
        var timer = opt.timer  //滚动的时间间隔（毫秒）

        //向左滚动函数
        function scrollLeft() {
            $btnLeft.unbind("click", scrollLeft); //滑动时先取消点击滑动事件
            $btnRight.unbind("click", scrollRight);
            $this.animate({
                marginLeft : -liW
            }, speed, function () {
                $this.find(elemClass+":first").appendTo($this);
                $this.css({'margin-left' : 0});
                $btnLeft.bind("click", scrollLeft); //滑动结束后绑定按钮的点击事件
                $btnRight.bind("click", scrollRight);
            });
        }
        //向右滚动函数
        function scrollRight() {
            $btnLeft.unbind("click", scrollLeft);
            $btnRight.unbind("click", scrollRight);
            $this.find(elemClass+":last").prependTo($this);
            $this.css({'margin-left' : -liW});
            $this.animate({
                marginLeft : 0
            }, speed, function () {
                $btnLeft.bind("click", scrollLeft);
                $btnRight.bind("click", scrollRight);
            });
        }
        //自动播放
        function autoPlay() {
            if ( timer )
                timerID = window.setInterval(scrollLeft, timer);
        }

        //停止自动播放
        function autoStop() {
            if ( timer )
                window.clearInterval(timerID);
        }

        //鼠标事件绑定
        $this.hover(autoStop, autoPlay).trigger("mouseout"); //加载完成后自动开始
        $btnLeft.click(scrollLeft).hover(autoStop, autoPlay)//向左鼠标事件绑定
        $btnRight.click(scrollRight).hover(autoStop, autoPlay)//向右鼠标事件绑定
    }

    /*
     * 提示信息
     * @param opt.type 提示类型
     * @param opt.message 提示信息
     * */
    exports.showTip = function(opt){
        var type = opt.type,
            message = opt.message,
            top = opt.top ? opt.top : 30,
            color,tem;
        switch(type){
            case "error":
                color = "red";
                break;
            case "warning":
                color = "#F60";
                break;
            case "success":
                color = "green";
                break;
        }
        tem = '<p id="J_ShowTip" style="position:fixed; color: '+color+'; top: '+top+'px; _position: absolute; _top: expression(eval(document.documentElement.scrollTop+'+top+')); height: 30px; width: 100%; line-height: 30px; font-weight: bold; text-align:center;border-bottom: 1px solid #DDD; padding: 0 10px; background: ivory;">'+message+'</p>';
        if($("#J_ShowTip").length){
            $("#J_ShowTip").text(message);
            $("#J_ShowTip").css({"color":color});
            $("#J_ShowTip").show();
        }else{
            $("body").append($(tem));
        }
        $("#J_ShowTip").delay(5000).slideUp();
    }
});